package com.example.programme.home;





import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;


import android.content.DialogInterface;
import android.content.Intent;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;


import android.view.LayoutInflater;



import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.widget.PopupWindow;

import com.example.programme.DetailActivity;
import com.example.programme.MyToast;
import com.example.programme.R;
import com.example.programme.Items.WordItem;
import com.example.programme.database.DBHelper;
import com.example.programme.database.DBManager;

public class WordsBaseFragment extends Fragment implements
        AdapterView.OnItemClickListener,AdapterView.OnItemLongClickListener {
    private static final String TAG = "提示";
    DBHelper dbHelper = new DBHelper(getActivity());
    ListView listView;
    List<Map<String, Object>> list;
    PopupWindow window;
    private SimpleAdapter listAdapter; // 适配器
    SwipeRefreshLayout swipeRefreshLayout;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_wordsbase, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        dbHelper = new DBHelper(getActivity());
        DBManager dbManager = new DBManager(getActivity());
         updatelistview();//显示数据库中单词

        /**
         * 弹窗设置+开启弹窗
         */
        View popup_view = getLayoutInflater().inflate(R.layout.popu_view, null);
        EditText input_English = popup_view.findViewById(R.id.input_English);
        EditText input_Chinese = popup_view.findViewById(R.id.input_Chinese);
        EditText input_Cixing = popup_view.findViewById(R.id.input_Cixing);
        ImageView addone = popup_view.findViewById(R.id.addone);

        window = new PopupWindow(popup_view, ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);//true 很关键

        window.setTouchable(true);
        window.setOutsideTouchable(true);
        window.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));
        //window.setBackgroundDrawable(getResources().getDrawable(R.drawable.img));//弹窗的样式

        ImageView tj = getActivity().findViewById(R.id.tj);
        tj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                window.showAsDropDown(view);//对应改为popu_view
            }
        });
        //弹窗内的事件处理
          //添加
        addone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String english = input_English.getText().toString().trim();
                String chinese = input_Chinese.getText().toString().trim();
                String cixing = input_Cixing.getText().toString().trim();
                Log.i(TAG, "input: " + english);
                Log.i(TAG, "input: " + cixing);
                Log.i(TAG, "input: " + chinese);

                Tianjia(english, cixing, chinese);
            }
        });
         //操作刷新
        ImageView redo=popup_view.findViewById(R.id.redo);
        redo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updatelistview();
                MyToast.makeText(getActivity(),"已刷新",Toast.LENGTH_SHORT);
            }
        });
        //滑动刷新
        swipeRefreshLayout = getActivity().findViewById(R.id.list_refresh);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                updatelistview();
                swipeRefreshLayout.setRefreshing(true);
            }
        });
    }

    //添加单词
    private void Tianjia(String english, String cixing, String chinese) {
        if (!TextUtils.isEmpty(english) && !TextUtils.isEmpty(cixing) && !TextUtils.isEmpty(chinese)) {
            //连接数据库
              boolean flag1=false;
            DBManager dbManager = new DBManager(getActivity());
            if (dbManager.listAll() != null) {//调用方法获取数据库中的单词
                for (WordItem word : dbManager.listAll()) {

                    if (word.getEnglish().equals(english) ) {
                        flag1=true;//有重复的数据
                    }
                }
                //添加新数据
                if(flag1==false){
                    dbManager.add(english,cixing,chinese);
                    MyToast.makeText(getActivity(), "添加成功", Toast.LENGTH_LONG);
                }
                //更新重复的数据
                else {
                    dbManager.update(english,cixing,chinese);
                    MyToast.makeText(getActivity(), "更新成功", Toast.LENGTH_SHORT);
                }
            }
            else dbManager.add(english,cixing,chinese);
            updatelistview();
        }
         else MyToast.makeText(getActivity(), "请正确输入信息", Toast.LENGTH_LONG);
    }


    //更新页面数据
    private void updatelistview() {
        listView = getActivity().findViewById(R.id.list2);
        listView.setOnItemClickListener(this);
        listView.setOnItemLongClickListener(this);
        list = new ArrayList<Map<String, Object>>();

        /**
         * 把单词添加到列表组里
         */
        DBManager dbManager = new DBManager(getActivity());
        if (dbManager.dxlistALL() !=null){
        for (WordItem word:dbManager.dxlistALL()) {//获取数据库中的单词
            Map<String, Object> map = new HashMap<>();
            map.put("id", word.getId() + ".");
            map.put("word", word.getEnglish());
            map.put("cixing",word.getCixing());
            map.put("translate", word.getChinese());
            list.add(map);
        }
            //生成适配器的Item,和动态数组对应的元素
            listAdapter = new SimpleAdapter(getActivity(), list, R.layout.words_item,
                new String[]{ "word","cixing" ,"translate"}, new int[]{ R.id.word,R.id.cixing, R.id.translate});

        listView.setAdapter(listAdapter);
      }
    }


    // 重写方法,点击事件处理
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

            Log.i(TAG,"OnItemClick: ");
            //获得数据项
            HashMap<String, String> map = (HashMap<String, String>) listView.getItemAtPosition(position);

            Log.i(TAG, "onItemClick: 打开新窗口");
            Intent Itemclick = new Intent(getActivity(), DetailActivity.class);
            String word = map.get("word");
            String cixing= map.get("cixing");

            String translate = map.get("translate");

             Itemclick.putExtra("word_key", word);
             Itemclick.putExtra("cixing_key", cixing);
             Itemclick.putExtra("translate_key", translate);

             startActivity(Itemclick);

        }

//长按处理
    @Override
    public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long l) {
        //删除操作
        //构造对话框进行确认操作
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("提示").setMessage("请确认是否删除当前数据")
                .setPositiveButton("是",new DialogInterface.OnClickListener(){

            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.i(TAG, "onClick: 对话框事件处理");
                HashMap<String, String> map = (HashMap<String, String>) listView.getItemAtPosition(position);

                DBManager dbManager = new DBManager(getActivity());
                String str = "";
                if (dbManager.listAll() != null) {
                    for (WordItem word : dbManager.listAll()) {//获取数据库中的单词
                        if (word.getEnglish().equals( map.get("word")))
                            str = word.getEnglish();
                    }
                    dbManager.delete(str);//删除
                    list.remove(position);
                    listAdapter.notifyDataSetChanged();
                }
            }
        }).setNegativeButton("否",null);
        builder.create().show();
        Log.i(TAG, "onItemLongClick: size=" + list.size());
        return true;
    }

}




